package com.sihan.framework.etm.service.impl;

import com.framework.mybatis.Condition;
import com.framework.mybatis.service.impl.BaseServiceImpl;
import com.framework.util.WebUtils;
import com.sihan.framework.etm.entity.CodeSTD;
import com.sihan.framework.etm.entity.Org;
import com.sihan.framework.etm.entity.User;
import com.sihan.framework.etm.mapper.CodeMapper;
import com.sihan.framework.etm.mapper.OrgMapper;
import com.sihan.framework.etm.mapper.UserRoleMapper;
import com.sihan.framework.etm.service.CodeService;
import com.sihan.framework.etm.vo.RoleVO;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CodeServiceImpl extends BaseServiceImpl<CodeSTD, String> implements CodeService {

	@Autowired
    private CodeMapper codeMapper;
	
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	@Autowired
	private OrgMapper orgMapper;
	
    @Override
    public List<Map<String, Object>> getCodeByType(String codeType) {
    	return codeMapper.getCodeByType(codeType);
    }
    
    @Override
    public Boolean isAdmin() {
    	User user = WebUtils.user();
		List<RoleVO> roles = userRoleMapper.selectRolesByUserId(user.getId());
		if(roles != null && roles.size() > 0) {
			for(RoleVO role : roles) {
				if(role.getId() == "1") {
					return true;
				}
			}
		}
		return false;
    }
    
    @Override
    public String getOrgId() {
    	String orgId = null;
		if(!isAdmin()) {
			User user = WebUtils.user();
			Org org = orgMapper.selectOne(new Condition<>(new Org(user.getCompanyCode(),false,(short)0)));
			orgId = org != null ? org.getId() : null;
		}
		return orgId;
    }

	@SuppressWarnings("unchecked")
	@Override
	public void updateCode(String code,Object value) {
		CodeSTD codeSTD = codeMapper.selectOne(new Condition<CodeSTD>().eq("code_type",code));
		if(null != codeSTD) {
			codeSTD.setValue(value.toString());
			codeMapper.updateById(codeSTD);
		}
	}
}
